from rest_framework import serializers
from .models import FontCategory, Font


class FontCategorySerializer(serializers.ModelSerializer):
    """字体分类详情列化器"""

    class Meta:
        model = FontCategory
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'sort_order']


class CreateFontCategorySerializer(serializers.ModelSerializer):
    """创建字体分类序列化器"""

    class Meta:
        model = FontCategory
        fields = ['name', 'code', 'description']


class UpdateFontCategorySerializer(serializers.ModelSerializer):
    """更新字体分类序列化器"""

    class Meta:
        model = FontCategory
        fields = ['name', 'description']


class FontSerializer(serializers.ModelSerializer):
    """字体详情序列化器"""
    file_url = serializers.SerializerMethodField()
    preview_image = serializers.SerializerMethodField()

    class Meta:
        model = Font
        fields = '__all__'
        read_only_fields = ['id', 'created_at']

    def get_file_url(self, obj):
        """返回不带media前缀的字体文件URL"""
        if obj.file_url:
            return obj.file_url.name
        return None

    def get_preview_image(self, obj):
        """返回不带media前缀的预览图URL"""
        if obj.preview_image:
            return obj.preview_image.name
        return None


class CreateFontSerializer(serializers.ModelSerializer):
    """创建字体序列化器"""

    class Meta:
        model = Font
        fields = ['category', 'name', 'family', 'file_format', 'font_weight',
                  'font_style', 'is_system']


class UpdateFontSerializer(serializers.ModelSerializer):
    """更新字体序列化器"""

    class Meta:
        model = Font
        fields = ['category', 'name', 'family', 'is_favorite', 'font_weight',
                  'font_style']
